"""
@Author：十
@Time：2024/6/18 10:33
@FileName：main.py
@Description：主线程及主UI
"""
import ctypes
import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication

from picosdk.functions import assert_pico_ok
from picosdk.ps5000a import ps5000a as ps

from mainUI import Ui_Form

status = {}
chandle = ctypes.c_int16()


class MainWindow(QWidget, Ui_Form):
    start_print = pyqtSignal()

    def __init__(self):

        super().__init__()

        self.setupUi(self)

        self.pushButton_Start.clicked.connect(self.Start_Pico)
        self.pushButton_Stop.clicked.connect(self.Stop_Pico)

    def Start_Pico(self):
        global chandle
        resolution = ps.PS5000A_DEVICE_RESOLUTION["PS5000A_DR_12BIT"]
        status["openunit"] = ps.ps5000aOpenUnit(ctypes.byref(chandle), None, resolution)
        try:
            assert_pico_ok(status["openunit"])
        except:
            powerStatus = status["openunit"]
            if powerStatus == 286:
                status["changePowerSource"] = ps.ps5000aChangePowerSource(chandle, powerStatus)
            elif powerStatus == 282:
                status["changePowerSource"] = ps.ps5000aChangePowerSource(chandle, powerStatus)
            else:
                raise
            assert_pico_ok(status["changePowerSource"])
        channel = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
        coupling_type = ps.PS5000A_COUPLING["PS5000A_AC"]
        self.Range['chARange'] = ps.PS5000A_RANGE["PS5000A_5V"]
        status["setChA"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, self.Range['chARange'], 0)
        assert_pico_ok(status["setChA"])
        channel = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_B"]
        self.Range['chBRange'] = ps.PS5000A_RANGE["PS5000A_5V"]
        status["setChB"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, self.Range['chBRange'], 0)
        assert_pico_ok(status["setChB"])
        channel = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_C"]
        self.Range['chCRange'] = ps.PS5000A_RANGE["PS5000A_5V"]
        status["setChC"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, self.Range['chCRange'], 0)
        assert_pico_ok(status["setChC"])
        channel = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_D"]
        self.Range['chDRange'] = ps.PS5000A_RANGE["PS5000A_5V"]
        status["setChD"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, self.Range['chDRange'], 0)
        assert_pico_ok(status["setChD"])
        status["maximumValue"] = ps.ps5000aMaximumValue(chandle, ctypes.byref(self.maxADC))
        assert_pico_ok(status["maximumValue"])

    def Stop_Pico(self):
        global chandle
        try:
            ps.ps5000aStop(chandle)
            ps.ps5000aCloseUnit(chandle)
        except Exception as e:
            print('Stop Exception:', e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
